package tags;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import statics.SoptVars;

import comm.parsers.NaverRangkingResultSAXParserHandler;
import comm.util.CommUtil;
import comm.util.SoptHashMap;

public class PortalTagManager {
	public PortalTagManager() {
		// TODO Auto-generated constructor stub
	}
	
	//현재 이슈 키워드 가져오기 ( 다음, 네이버 믹스 )
	public ArrayList getCurrentIssueMixedKeyword(){
		ArrayList Bothlt = new ArrayList();
		
		ArrayList daum = getDaumIssueRanking();
		ArrayList naver = getNaverIssueRanking();
		
		for (int i = 0; i < daum.size(); i++) {
			for (int j = 0; j < naver.size(); j++) {
				if(daum.get(i).toString().equals( naver.get(j).toString())){
					naver.remove(j);
				}
			}
		}
		
		for (int k = 0; k < naver.size(); k++) {
			daum.add(naver.get(k));
		}
		naver = null;
		
//		System.out.println("랜덤 화 전 "+daum.toString());
		
		daum = CommUtil.RandomizeArrayList(daum);
		
//		System.out.println("랜덤 화 후 "+daum.toString());		
		
		return daum;
	}
	
	public String getPageContentStr(String reqStr,String encoding){
		
		if(encoding==null || encoding.length()==0)encoding="UTF-8;";
		if(reqStr==null || reqStr.length()==0)return "";
		
		URL url = null;//URL 주소 객체
        URLConnection connection;//URL접속을 가지는 객체
        InputStream is;//URL접속에서 내용을 읽기위한 Stream
        InputStreamReader isr;
        BufferedReader br;
        String result = "";
        
		 try{
	         //URL객체를 생성하고 해당 URL로 접속한다..
			 reqStr = reqStr;
	            
	            					
            url = new URL(reqStr);
            connection = url.openConnection();
            

            //내용을 읽어오기위한 InputStream객체를 생성한다..
            is = connection.getInputStream();
            
            
            isr = new InputStreamReader(is,encoding);
            br = new BufferedReader(isr);
            
            //내용을 읽어서 화면에 출력한다..
            String buf = null;
            result = "";
            while(true){
                buf = br.readLine();
                if(buf!=null)result+=buf;
                else break;
                
                //System.out.println(buf);
            }
        }catch(MalformedURLException mue){
            System.err.println("잘못되 URL입니다. 사용법 : java URLConn http://hostname/path]");
            System.exit(1);
        }catch(IOException ioe){
            System.err.println("IOException " + ioe);
            ioe.printStackTrace();
            System.exit(1);
        }
        return result;
	}
	
	public ArrayList getDaumIssueRanking(){
		ArrayList lt = new ArrayList(); 
		String first = getPageContentStr("http://apis.daum.net/ajax/rtissue.daum?apikey="+SoptVars.DaumAJAXAAPIKEY,"UTF-8");
		
//		System.out.println("=========일단 페이지 내용 보자");
//		System.out.println(first);
		
		String issuePage = "http://img.search.daum-img.net/jumpkeyword//tot.js";
		
//		System.out.println("=========일단 페이지 내용 보자");
		String third = getPageContentStr(issuePage,"EUC-KR");
		
		
		third = third.substring(third.indexOf("["),third.lastIndexOf("]")+1);
		
		//System.out.println(third );
		
		try {
			JSONArray jsonArray = new JSONArray(third);
			
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject tempObj = new JSONObject(jsonArray.get(i).toString());
				SoptHashMap hm = new SoptHashMap();
				hm.put("R", i+1);
				hm.put("K", tempObj.getString("K"));
				lt.add(hm);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//System.out.println("다음 랭킹======");
		//System.out.println(lt.toString());
		
		return lt;
	}
	
	public ArrayList getNaverIssueRanking(){
		ArrayList Naverlt = new ArrayList();
		
		String reqStr = "http://openapi.naver.com/search?key="+SoptVars.naverKey+"&query=nexearch&target=rank";
		
		NaverRangkingResultSAXParserHandler soptDh = new NaverRangkingResultSAXParserHandler();
		
		try{
			SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
			parser.parse(reqStr, soptDh);
			
			ArrayList tempLt = soptDh.getItemList();
			
			for (int i = 0; i < tempLt.size(); i++) {
				SoptHashMap hm = new SoptHashMap();
				hm.put("R", i+1);
				hm.put("K", tempLt.get(i));
				Naverlt.add(hm);
			}
		} catch (ParserConfigurationException e) {
			  e.printStackTrace();
		 } catch (SAXException e) {
		  e.printStackTrace();
		 } catch (IOException e) {
		  e.printStackTrace();
		 }
		
       
        //System.out.println("네이버 검색어 랭킹===========");
		//System.out.print(Naverlt.toString());
		
		return Naverlt;
	}
}
